<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">

      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <el-form :inline="true" :model="searchForm" ref="searchForm">
            <el-form-item>
              <el-button type="success" @click.stop="search">刷新</el-button>
              <el-button type="warning" @click.stop="add">添加</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div slot="header" class="clearfix">
          <el-alert title="注意：最多只能添加六张轮播图" type="warning">
          </el-alert>
        </div>
        <el-table :data="table" border>
          <el-table-column prop="id" label="ID" width="100"></el-table-column>
          <el-table-column label="图片" width="120">
            <template slot-scope="scope">
              <el-image style="width: 100px;" :src="scope.row.pic" :fit="fit"></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="path" label="跳转路径"></el-table-column>
          <el-table-column prop="sort" label="排序" width="70"></el-table-column>
          <el-table-column label="状态" width="70">
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" :content="scope.row.status == 1 ?'正常': '禁用'" placement="top" :enterable="false">
                <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="2" @change="changeStatus(scope.row)">
                </el-switch>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
            <template slot-scope="scope">
              {{scope.row.create_time|formatDate}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="edit(scope.row.id)">编辑</el-button>
              <el-button type="text" @click="del(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-dialog title="编辑轮播图" :visible.sync="editVisible" :before-close="handleClose" width="500px">
        <el-form ref="editForm" :model="editForm" label-width="100px" :rules="rules">
          <el-form-item label="图片" prop="pic">
            <el-upload ref="editImage" name="image" action="#" :on-change="handleImgChange" :on-remove="handleImgRemove" list-type="picture" :limit="1" :on-exceed="handleImgExceed" :auto-upload="false"
              :file-list="fileList">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过500kb，宽高建议375*160</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转地址" prop="path">
            <el-input v-model="editForm.path" placeholder="请输入跳转地址" clearable></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="editForm.sort" :min="1" :max="6" label="排序"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">编 辑</el-button>
        </span>
      </el-dialog>
      <el-dialog title="添加轮播图" :visible.sync="addVisible" :before-close="handleClose" width="500px">
        <el-form ref="addForm" :model="addForm" label-width="100px" :rules="rules">
          <el-form-item label="图片" prop="pic">
            <el-upload ref="addImage" name="image" action="#" :on-change="handleImgChange" :on-remove="handleImgRemove" list-type="picture" :limit="1" :on-exceed="handleImgExceed" :auto-upload="false">
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png/jpeg文件，且不超过500kb，宽高建议375*160</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转地址" prop="path">
            <el-input v-model="addForm.path" placeholder="请输入跳转地址" clearable></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="addForm.sort" :min="1" :max="6" label="排序"></el-input-number>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close()" size="small">取 消</el-button>
          <el-button type="primary" @click="send()" size="small">添 加</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { changeBannerStatus, getBannerList, getBannerOnly, addBanner, editBanner, delBanner } from '@/network/api.js'

export default {
  name: 'banner',
  data() {
    return {
      searchForm: {},
      table: [],
      editForm: {
        id: 0,
        path: '', // 名称
        pic: '', // 图片
        sort: 1 // 排序
      },
      // 添加表单
      addForm: {
        path: '', // 名称
        pic: '', // 图片
        sort: 1 // 排序
      },
      actFormName: '',
      actUploadName: '',
      actvisibleName: '',
      fileList: [],
      editVisible: false, // 编辑
      addVisible: false, // 添加
      rules: {
        path: [{ required: true, message: '地址必须', trigger: 'blur' }],
        pic: [{ required: true, message: '图片必须', trigger: 'change' }],
        sort: [
          { required: true, message: '排序必须', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^[1-6]$/.test(value)) {
                callback(new Error('请输入合法的排序'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.search()
  },
  computed: {},
  methods: {
    // 添加文件
    handleImgChange(file, fileList) {
      if (file && file.status === 'ready') {
        // 判断文件类型
        const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
        if (imageType.indexOf(file.raw.type) === -1) {
          this.$message.error('请上传png|jpg|jpeg图片')
          return this.$refs[this.actUploadName].clearFiles()
        }
        if (file.size > 1024 * 400) {
          this.$message.error('请上传小于500kb图片')
          return this.$refs[this.actUploadName].clearFiles()
        }
        this[this.actFormName].pic = file.raw
        this.$refs[this.actFormName].clearValidate('pic')
      }
    },
    handleImgRemove(file, fileList) {
      // console.log(file)
      // if (file && file.status === 'ready') {
      // 移除方法
      this[this.actFormName].pic = ''
      // console.log(this[this.actFormName])
      this.$refs[this.actFormName].validateField('pic')
      // }
    },
    // 超出上传个数
    handleImgExceed(files, fileList) {
      this.$message.error('已有pic图片请先删除')
    },
    // 联动删除
    handleChange(data) {
      this.$refs[this.actFormName].clearValidate()
    },
    async search() {
      try {
        const rtn = await getBannerList(this.searchForm)
        this.table = rtn
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 添加
    add() {
      if (this.table.length >= 6) {
        return this.$message.error('最多添加6张轮播图')
      }
      this.actFormName = 'addForm'
      this.actUploadName = 'addImage'
      this.actvisibleName = 'addVisible'
      this.addVisible = true
    },
    // 修改状态
    changeStatus(ev) {
      let msg = ''
      let oldStatus = ''
      switch (ev.status) {
        case 1:
          msg = '您确定要启用该轮播图吗?'
          oldStatus = 2
          break
        case 2:
          msg = '此操作将禁用该轮播图, 是否确定?'
          oldStatus = 1
          break
        default:
          return this.$message.error('不可用的操作')
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(async () => {
          try {
            await changeBannerStatus({ id: ev.id, status: ev.status })
          } catch (e) {
            ev.status = oldStatus
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          ev.status = oldStatus
          this.$message.warning('您已取消操作')
        })
    },
    // 删除
    del(id) {
      this.$confirm('您确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
        .then(async () => {
          try {
            await delBanner({ id })
            this.search()
          } catch (e) {
            this.$message.error(e.message)
          }
        })
        .catch(() => {
          this.$message.warning('您已取消操作')
        })
    },
    // 编辑
    async edit(id) {
      try {
        const rtn = await getBannerOnly({ id })
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn
          this.fileList = [{ url: [rtn.pic] }]
          this.actFormName = 'editForm'
          this.actvisibleName = 'editVisible'
          this.actUploadName = 'editImage'
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    myClose() {
      this.$refs[this.actFormName].resetFields()
      this[this.actFormName].pic = ''
      // this[this.actFormName].template_id = ''
      // if (this.actFormName === 'addForm') {
      //   this.addForm.pid = []
      // }
      // this.editPic = []
      this.$refs[this.actUploadName].clearFiles() // 删除预览
      // this.actFormName = ''
      // this.actUploadName = ''
    },

    // 关闭弹出前操作(不包括取消按钮)
    handleClose(done) {
      this.myClose()
      done()
    },
    // 取消按钮
    close() {
      this.myClose()
      this[this.actvisibleName] = false
    },
    send() {
      this.$refs[this.actFormName].validate(async valid => {
        if (valid) {
          switch (this.actFormName) {
            case 'editForm': // 编辑司机
              try {
                await editBanner(this.editForm)
                this.close()
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'addForm': // 添加模板
              try {
                await addBanner(this.addForm)
                this.close()
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          this.$message.error('请检查表单')
          return false
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-cascader {
  width: 100%;
}
.input-with-select {
  width: 110px;
}
.middle {
  min-height: 60px;
  display: flex;
  align-items: center;
  padding-bottom: 20px;
  border-bottom: 1px solid #f2f2f2;
}
.middle:last-child {
  padding: 0;
  border: 0;
  padding-top: 20px;
}
.class-name {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}
.tag-right {
  margin: 2px;
  // padding: 5px;
}
</style>
